package com.zbs.framework.dao.user.service.impl;

import com.zbs.framework.common.utils.Constant;
import com.zbs.framework.common.utils.ErrEnum;
import com.zbs.framework.common.utils.ErrorAssert;
import com.zbs.framework.dao.passport.base.service.LoginRecordService;
import com.zbs.framework.dao.passport.entity.AcctWechat;
import com.zbs.framework.dao.passport.entity.MNAccount;
import com.zbs.framework.dao.passport.entity.MNLoginRecord;
import com.zbs.framework.dao.passport.wechat.service.WechatAccountService;
import com.zbs.framework.dao.user.UserConst;
import com.zbs.framework.dao.user.entity.BaseUserInfo;
import com.zbs.framework.dao.user.entity.MNBaseUser;
import com.zbs.framework.dao.user.model.LoginResult;
import com.zbs.framework.dao.user.repository.BaseUserRepository;
import com.zbs.framework.dao.user.repository.UserRoleRepository;
import com.zbs.framework.dao.user.service.BaseUserService;
import com.zbs.framework.dao.user.service.WechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Zbs
 * 2018-11-23 17:24
 */
@Service
@Transactional
public class WechatUserServiceImpl implements WechatUserService {

    @Autowired
    private WechatAccountService wechatAccountService;

    @Autowired
    private BaseUserRepository baseUserRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private LoginRecordService loginRecordService;

    @Override
    public LoginResult login(String code, String entryType) {
        // 参数检查
        ErrorAssert.hasLength(code, "Code can not be empty!");
        // 获取token
        SnsToken snsToken = wechatAccountService.getSnsToken(code);
        // 判断账号是否已存在
        MNAccount account = wechatAccountService.findAccount(snsToken.getOpenid());
        ErrorAssert.isTrue((account == null) || account.getEnabled().equals(Constant.YES),
                ErrEnum.ACCOUNT_IS_DISABLED);
        MNBaseUser baseUser;
        String acctUuid;
        Integer[] roleIds;
        if (account == null) {
            // 创建账号
            AcctWechat aw = wechatAccountService.create(snsToken.getOpenid());
            acctUuid = aw.getAcctUuid();
            // 创建基础用户
            // 获取微信用户信息
            User wxUser = wechatAccountService.getWechatUserInfo(snsToken);
            roleIds = new Integer[]{UserConst.ROLE_NORMAL};
            if (wxUser != null) {
                Character gender = wxUser.getSex().equals(1) ? UserConst.MALE : UserConst.FEMALE;
                baseUser = new MNBaseUser(aw.getAcctUuid(), wxUser.getNickname(),
                        gender, new Date(), UserConst.USER_TYPE_NORMAL, null,
                        wxUser.getHeadimgurl(), "");
            } else {
                String name = "uid_" + UUID.randomUUID().toString().replaceAll("-", "");
                baseUser = new MNBaseUser(aw.getAcctUuid(), name, UserConst.MALE,
                        new Date(), UserConst.USER_TYPE_NORMAL, null,
                        "", "");
            }
            // 修改用户角色信息
            baseUserService.saveUserRoles(baseUser.getId(), roleIds);
            baseUserRepository.save(baseUser);
        } else {
            acctUuid = account.getUuid();
            // 账号已存在，获取用户信息
            baseUser = baseUserRepository.findByAcctUuid(acctUuid);
            roleIds = userRoleRepository.findRoleIds(baseUser.getId());
        }
        MNLoginRecord record = loginRecordService.refresh(acctUuid, entryType);
        BaseUserInfo userInfo = new BaseUserInfo(baseUser, roleIds);
        //
//        afterUserLogin(session, userInfo, record);
//        return new LoginResult(record.getToken(), session.getId(), userInfo);
        return null;
    }

//    private void afterUserLogin(HttpSession session, BaseUserInfo userInfo, MNLoginRecord record) {
//        // 处理session
//        SessionUser sessionUser = new SessionUser(userInfo.getId(),
//                userInfo.getName(), userInfo.getRoleIds());
//        session.setAttribute("sessionUser", sessionUser);
//        // 事务提交后发送消息
//        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
//            @Override
//            public void afterCommit() {
//                // MQ发送用户登录消息
//                applicationContext.publishEvent(new UserLoggedInEvent(this, session,
//                        record.getUuid(), record.getEntryType(), userInfo.getId(), userInfo.getName()));
//            }
//        });
//    }
}
